package com.itcanteen.medical.common.advice;

import com.itcanteen.medical.common.annotation.IngoreResponseAdvice;
import com.itcanteen.medical.common.vo.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 *
 * 增强--》干预
 */
@RestControllerAdvice
@Slf4j
public class CommonResponseDataAdvice implements ResponseBodyAdvice<Object> {

    /**
     * 判断是否需要增强
     * @param returnType
     * @param converterType
     * @return
     */
    @Override
    public boolean supports(MethodParameter returnType,
                            Class<? extends HttpMessageConverter<?>> converterType) {
        log.info("CommonResponseDataAdvice->supports");

       if(returnType.getDeclaringClass().isAnnotationPresent(IngoreResponseAdvice.class)) {
            return false;
        }
        if(returnType.getMethod().isAnnotationPresent(IngoreResponseAdvice.class)){
           return false;
        }
        return true;
    }


    /**
     * 增强的逻辑:拦截@@RestController的类，拿到返回结果，进行增强
     * @param body
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object body,
                                  MethodParameter returnType,
                                  MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {
        log.info("body->{}",body);

        CommonResponse<Object> commonResponse = new CommonResponse<>(0, "success");
        if(body==null){
            return commonResponse;
        }else if(body instanceof CommonResponse){
            commonResponse =  (CommonResponse<Object>)body;
        }else{
            commonResponse.setData(body);
        }

        return commonResponse;
    }



}
